package java8;

import java8.entity.Employee;

import java.util.Arrays;
import java.util.List;

public class ReduceDemo {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        // 第一个参数是累加的初始值 后面的函数是用阶段性的累加结果加上后面的参数
        Integer total = numbers.stream().reduce(0, (subtotal, element) -> subtotal + element);
        System.out.println("total = " + total);

        Integer total1 = numbers.stream().reduce(0, Integer::sum);
        System.out.println("total1 = " + total1);

        //这里还可以用作字符串的操作
        List<String> str = Arrays.asList("a", "b", "c", "d", "e", "g", "h");
        String strS = str.stream().reduce("", String::concat);
        System.out.println("strS = " + strS);

        //这个东西也可以在对象集合之中使用
        Employee e1 = new Employee(1, 22, "F", "aa", "aa");
        Employee e2 = new Employee(2, 23, "M", "bb", "bb");
        Employee e3 = new Employee(3, 24, "F", "cc", "cc");
        Employee e4 = new Employee(4, 25, "M", "dd", "dd");
        Employee e5 = new Employee(5, 26, "M", "ee", "ee");
        Employee e6 = new Employee(6, 27, "F", "gg", "gg");

        List<Employee> employees = Arrays.asList(e1, e2, e3, e4, e5, e6);
        //用并行流进行运算效率会有很大的提高 (第三个参数是合并器)求和
        Integer total2 = employees.stream().parallel().map(e -> e.getAge())
                .reduce(0, Integer::sum, Integer::sum);
        System.out.println("total2 = " + total2);

        //这里的合并器相当于是把 Employee 类型转化为了 Integer 类型
        Integer total3 = employees.stream().parallel()
                .reduce(0, (subtotal, emp) -> subtotal + emp.getAge(), Integer::sum);
        System.out.println("total3 = " + total3);

    }
}
